<template>
  <view class="container">
    <!-- 搜索框 -->
    <view class="map-info">
      <view class="map-info-item" @tap="selectCity">
        <view class="map-search">
          <input v-model="keywords" type="text" class="u-text" placeholder="搜索小区名称" @input="selectCity" />
          <text class="u-btn" @tap="selectCity">搜索</text>
        </view>
      </view>
    </view>

    <!-- 地图容器 -->
    <view id="map" class="map-container"></view>
  </view>
</template>

<script>
import { getCommunityPage } from '@/api/community';
const mapKey = 'Cq5k13fcUNmZCyzpI7szHrVdF5pwH9O6';
// 添加aimap的引入
const script = document.createElement('script');
script.src = 'https://location-dev.newayz.com/aimap-gl-js/v2.6.0/aimap-gl.js';
document.head.appendChild(script);

const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = 'https://location-dev.newayz.com/aimap-gl-js/v2.6.0/aimap-gl.css';
document.head.appendChild(link);
export default {
  data() {
    return {
      keywords: '',
      list: [],
      map: null,
      queryData: {},
      otherParam: {},
    };
  },

  onLoad() {
    // 获取地址栏参数
    // const query = this.getQueryParams();
    // const { type, pageName, teamLeaderId, ...rest } = query;
    // this.otherParam = { type, pageName, teamLeaderId };
    // this.queryData = rest;

    this.getCommunityList();
  },

  methods: {
    // 获取URL参数
    getQueryParams() {
      const url = decodeURIComponent(window.location.href);
      const queryString = url.split('=')[1];
      return JSON.parse(queryString);
    },

    // 获取小区列表
    async getCommunityList() {
      // const params = this.queryData;
      const params = {};

      try {
        const res = await this.getList(1);
        console.log('res', res);

        const total = res.count || 0;
        const listLen = res.lists.length || 0;

        this.list = total > listLen ? await this.allList(total) : res.lists;

        this.initMap();
      } catch (error) {
        console.error('获取小区列表失败：', error);
      }
    },

    // 获取分页数据
    getList(pageNo) {
      return new Promise((resolve, reject) => {
        getCommunityPage({ limit: 100, page: pageNo }).then(res => {
          resolve(res);
        });
      });
    },

    // 获取所有数据
    async allList(total) {
      try {
        const totalPages = Math.ceil(total / 100);
        let allData = [];

        for (let pageNo = 1; pageNo <= totalPages; pageNo++) {
          const response = await this.getList(pageNo);
          allData = allData.concat(response.list);
        }

        return allData;
      } catch (error) {
        console.error('获取所有数据失败：', error);
        return [];
      }
    },

    // 初始化地图
    initMap() {
      if (!this.list.length) return;

      aimap.accessToken = 'Cq5k13fcUNmZCyzpI7szHrVdF5pwH9O6';

      this.map = new aimap.Map({
        container: 'map',
        center: [this.list[0].lng, this.list[0].lat],
        zoom: 14,
        minZoom: 3,
        maxZoom: 20,
        style: 'aimap://styles/aimap/darkblue-v4',
      });

      // 添加导航控件
      const nav = new aimap.NavigationControl({
        showCompass: false,
      });
      this.map.addControl(nav, 'bottom-right');

      // 添加标记点
      this.addMarkers();
    },

    // 添加标记点
    addMarkers() {
      this.list.forEach(item => {
        const type = !item?.teamLeaderId ? 0 : item?.teamLeaderId === this.otherParam.teamLeaderId ? 1 : 2;

        const div = document.createElement('div');
        div.addEventListener('click', () => this.handleMarkerClick(item));
        div.innerHTML = `<p id="popup_${item.id}">${item.name}</p>`;

        new aimap.Popup({
          closeButton: false,
          closeOnClick: false,
          className: this.getPopupClass(type),
        })
          .setLngLat([item.lng, item.lat])
          .setDOMContent(div)
          .addTo(this.map);
      });
    },

    // 获取弹窗样式类名
    getPopupClass(type) {
      switch (type) {
        case 1:
          return 'type1-class';
        case 2:
          return 'type2-class';
        default:
          return 'type-other';
      }
    },

    // 处理标记点点击
    handleMarkerClick(item) {
      const type = !item?.teamLeaderId ? 0 : item?.teamLeaderId === this.otherParam.teamLeaderId ? 1 : 2;

      if (type === 1) {
        uni.showToast({
          title: `小区【${item.name}】已被我关联`,
          icon: 'none',
        });
        return;
      }

      if (type === 2) {
        uni.showToast({
          title: `小区【${item.name}】已被其他主理人关联`,
          icon: 'none',
        });
        return;
      }

      uni.showModal({
        title: '温馨提示',
        content: `是否关联【${item.name}】?`,
        success: res => {
          if (res.confirm && item.isCanBuy === 1) {
            this.handleConfirm(item);
          }
        },
      });
    },

    // 处理确认关联
    async handleConfirm(item) {
      try {
        const res = await uni.request({
          url: '/app-api/txjmk/app/teamleader/info/getCommunityByTeamLeaderRegionalPage',
          method: 'GET',
          data: {
            teamLeaderId: this.otherParam.teamLeaderId,
            communityId: item.id,
            id: this.queryData.id,
          },
        });

        if (res) {
          // 发送消息给小程序
          if (window.wx && wx.miniProgram) {
            wx.miniProgram.postMessage({
              data: {
                communityId: item.id,
                webViewMessageType: 'popup',
              },
            });
            wx.miniProgram.navigateBack({ delta: 1 });
          }
        }
      } catch (error) {
        console.error('关联小区失败：', error);
      }
    },

    // 搜索小区
    selectCity() {
      // const data = {
      //   longitude: this.longitude,
      //   latitude: this.latitude,
      //   teamLeaderId: this.teamLeaderId,
      // };
      // uni.navigateTo({
      //   url: `pages/link_community/mapSelect-list?data=${JSON.stringify(data)}`,
      // });
      uni.navigateTo({
        url: `pages/link_community/mapSelect-list`,
      });
    },
  },
};
</script>

<style lang="scss">
.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.map-info {
  padding: 30rpx 30rpx 10rpx;
  background-color: #fff;
  border-radius: 10rpx 10rpx 0 0;

  .map-info-item {
    position: fixed;
    top: 00rpx;
    left: 0;
    right: 0;
    z-index: 9;
    background-color: #fff;

    .map-search {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 20rpx;
      line-height: 60rpx;
      border: 1rpx solid #eee;
      border-radius: 50rpx;

      .u-text {
        flex: 1;
        line-height: 60rpx;
        padding-left: 30rpx;
        font-size: 26rpx;
        color: #333;
      }

      .u-btn {
        display: block;
        width: 120rpx;
        height: 60rpx;
        line-height: 60rpx;
        font-size: 26rpx;
        color: #5ff0a3;
        text-align: center;
      }
    }

    .map-addre {
      display: flex;
      justify-content: space-between;
      align-items: center;
      line-height: 60rpx;

      .now {
        flex: 1;
        font-size: 26rpx;
        color: #333;
      }

      .location {
        color: #666;
      }
    }
  }
}
.search-box {
  padding: 20rpx;
  background: #fff;
}

.map-container {
  flex: 1;
  width: 100%;
}

:deep(.type1-class) {
  border-color: #59efa4 !important;
  color: #59efa4 !important;
}

:deep(.type2-class) {
  border-color: #409eff !important;
  color: #333 !important;
}

:deep(.type-other) {
  border-color: #fa3534 !important;
  color: #333 !important;
}
</style>
